﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 

public class AutoReferenceObj
{
    //资源的引用对象
    private UnityEngine.Object owner = null;
    private Dictionary<string, UnityEngine.Object> dicRes = new Dictionary<string, UnityEngine.Object>();
    public AutoReferenceObj(UnityEngine.Object owner)
    {
        this.owner = owner;
    }
    /// <summary>
    /// 获取引用的id
    /// </summary>
    /// <returns></returns>
    public int GetOwnerId()
    { 
        int id = owner == null ? ResourceManager.NullOwnerId : owner.GetInstanceID();
        return id;
    }
    /// <summary>
    /// 获取加载对象
    /// </summary>
    /// <param name="address"></param>
    /// <returns></returns>
    public UnityEngine.Object GetObject(string address) 
    {
        UnityEngine.Object obj;
        if(dicRes.TryGetValue(address , out obj))
        {
            return obj;
        }
        return null;
    }
    /// <summary>
    /// 添加对象
    /// </summary>
    /// <param name="address"></param>
    /// <param name="obj"></param>
    public void AddObject(string address,UnityEngine.Object obj)
    {
        if (!dicRes.ContainsKey(address))
        {
            dicRes.Add(address, obj);
        }
    }
    /// <summary>
    /// 检测这个引用是否已经无效
    /// </summary>
    /// <returns></returns>
    public bool CheckDestroy()
    {
        if(owner == null)
        {
            List<string> addessList = dicRes.GetkeyList();
            foreach (string adress in addessList)
            {
                ResourceManager.Release(adress); 
            }
            dicRes.Clear();
            return true;
        }
        else
        {
            CheckRef();
        }
        return false;
    } 

    //检测失去引用的Asset数据
    private void CheckRef()
    {
        List<string> addessList = dicRes.GetkeyList();
        foreach (string adress in addessList)
        {
            ReferenceObj referenceObj = ResourceManager.GetAAReferenceObj(adress);
            if (referenceObj.IsDestroy())
            {
                dicRes.Remove(adress);
            }
        }
    }

    public override string ToString()
    {
        string addresData = this.owner == null ? "Owner：Null": "Owner：" + this.owner.name;
        addresData += "\n";
        List<string> addessList = dicRes.GetkeyList();
        foreach (string adress in addessList)
        {
            addresData += adress + "\n";
        }
        return addresData;
    }
}
